home *** CD-ROM | disk | FTP | other *** search
- Path: castle.nando.net!news
- From: actuary@nando.net@castle.nando.net (Bill McCarthy)
- Newsgroups: comp.lang.c
- Subject: Re: Recursion
- Date: Mon, 08 Apr 1996 13:33:56 -0400
- Organization: Not so good, but I'm working on it ;-)
- Message-ID: <E4UaxUKSAKsW089yn@castle.nando.net>
- References: <31624BC2.70D2@sooner.net>
- NNTP-Posting-Host: vyger609.nando.net
-
- In article <31624BC2.70D2@sooner.net>,
- Eddie Bush <edwbush@sooner.net> put down for all to see:
-
- >I am trying to construct a C function that will recursively convert
- >a string such as "1234" into it's integer equivelant (1234).
- >
- >Here is what I know:
- >1)if you subtract the character "0" from any of the other digits "1".."9"
- > you will get the integer value of that characer.
- > Example: "1" - "0" is equal to 1
- > "2" - "0" is equal to 2
- > .
- > .
- > .
- > "9" - "0" is equal to 9
- >2)the function should be called with a character pointer:
- > Such as: convert("1234");
- > making the prototype look something like:
- > int convert(char *p);
- >
- >Does anyone have an idea? This is sorta stumping me. I am aware of
- >atoi, but I am wanting to write a recursive function that does that --
- >for the fun of it. It's sort of a little puzzle to help me learn
- >recursion. Any ideas?
-
- Here's a simply solution:
-
- #include <ctype.h>
- int cvt(const char *s, int n) {
- return isdigit(*s) ? cvt(s+1,10*n+*s-'0') : n;}
- int convert(const char *s) {return cvt(s, 0);}
-
- Have fun figuring it out,
- Bill
-